<template>
  <div class="page-container page-container-create" :style="{height:HEIGHT+'px'}">
    <!--面包屑-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>自动化营销</el-breadcrumb-item>
        <el-breadcrumb-item>用户组管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{judgeForm.userGroupName == '' ? '添加用户组' : '编辑用户组'}}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!--添加用户分组-->
    <el-form :model="dataForm" :rules="dataFormRules" ref="dataForm" :size="size" :label-position="labelPosition" >
    <el-row class="search-input">
      <el-form-item v-if="false" prop="id">
        <el-input v-model="dataForm.id"></el-input>
      </el-form-item>
      <el-form-item label="用户分组名称：" prop="userGroupName" class="mb30">
        <el-input v-model.trim="dataForm.userGroupName"
                  minlength="3"
                  maxlength="30"
                  placeholder="请输入用户分组名称" style="width: 328px;" clearable></el-input>
        <!-- <div class="desc">请输入3-30个字符</div> -->
      </el-form-item>
      <el-form-item label="分组类型：" prop="groupType" class="mb30">
        <el-select v-model="dataForm.groupType" placeholder="选择分组类型" style="width: 328px;" clearable :popper-append-to-body="false">
          <el-option label="动态分组" value="1"></el-option>
          <el-option label="静态分组" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分组描述：" prop="groupDescription" class="mb40">
        <el-input type="textarea" v-model.trim="dataForm.groupDescription"
                  maxlength="100"
                  show-word-limit
                  placeholder="请输入" style="width: 515px;" clearable :rows="4"></el-input>
      </el-form-item>
    </el-row>
      <el-form-item label="筛选用户标签：">
        <!--用户标签-->
        <div class="tab-container mb40" v-if="deptType==0" >
          <el-tabs v-model="activeDeptId" @tab-click="handleClick()">
            <el-tab-pane v-for="item in deptOptions" :key="item.id" :name="item.id" :label="item.deptName"></el-tab-pane>
          </el-tabs>
        </div>

        <div class="t_r w100 deleteAll">
          <el-button type="text" :size="size" @click="resetChecked()">清除所有条件<i class="el-icon-delete"></i></el-button>
        </div>

        <!--用户标签内容-->
        <div class="tree mb170">
          <div class="leftTree">
            <el-tree
              ref="leftTree"
              :data="labelTree"
              show-checkbox
              default-expand-all
              node-key="id"
              :props="defaultProps"
              @check="checkLeft"
              highlight-current></el-tree>
          </div>
          <div class="rightTree">
            <div class="li">
              <template>
                <el-tree
                  ref="rightTree"
                  :data="labelTree2"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :props="defaultProps"
                  :indent="0"
                  @check="checkRight"
                  highlight-current
                  :expand-on-click-node="false">
                  <div class="custom-tree-node" slot-scope="{ node,data }" :class="data.secondStyle?'secondStyle':''">
                    <p><span>{{ node.label }} </span></p>
                    <span v-if="!data.children" class="noData t_l">暂无数据</span>
                  </div>
                </el-tree>
              </template>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <div style="text-align: center">
          <el-row class="mb20">
            <el-button type="primary" class="filterBtn" @click="handlerStartScreening()">开始筛选</el-button>
          </el-row>
          <el-row class="mb80">
            <span class="turnInlineBlock font12">共为您筛选出</span>
            <el-tag style="min-width: 100px;vertical-align:middle" class="font12">{{dataForm.userGroupNumber}}</el-tag>
            <span class="turnInlineBlock font12">名会员</span>
          </el-row>
          <el-row style="margin-bottom: 30px;">
            <el-button type="primary" class="mr60 resetButton" @click="handlerCancel()" size="small">取消</el-button>
            <el-button type="primary" class="searchButton" @click="handlerSubmit()" size="small">确认</el-button>
          </el-row>
        </div>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
  import KtButton from '@/views/Core/KtButton'

  export default {
    components: {
      KtButton
    },

    data() {
      return {
        activeDeptId: 0,
        deptType: localStorage.getItem('deptType'),     // 当前登录用户所属组织类型
        userGroupId: this.$route.params.userGroupId,        // 得到用户组id
        deptOptions: [],
        HEIGHT: window.innerHeight,
        size: 'mini',
        labelPosition: 'right',
        dataForm: {
          userGroupName: '',
          groupType: '',
          groupDescription: '',
          userGroupNumber: null
        },
        judgeForm: {
          userGroupName: '',
          groupType: '',
          groupDescription: '',
          userGroupNumber: null
        },
        dataFormRules: {
          userGroupName: [{required: true, min: 3, max: 30, message: '请输入用户分组名称', trigger: 'blur'}],
          groupType: [{required: true, message: '请选择分组类型', trigger: 'change'}]
        },
        labelTree: [],
        labelTree2: [],
        defaultProps: {
          children: 'children',
          label: 'labelName'
        },

        saveAllLabel: [],                                  // 保存当前部门所有选中标签
        currentSelectedDeptId: '',                         // 当前选中部门id
        selectRightIds:[],                                 //选中的数据
      }
    },

    methods: {
      // 得到用户组详情
      getUserGroupDetail: function () {
        let this_ = this
        this.utils.request.getUserGroupDetail({id: this.userGroupId}, res => {
          if (res.code == '0000') {
            this_.dataForm = Object.assign({}, res.data)
            this_.judgeForm = Object.assign({}, res.data)
            if (this_.dataForm.groupType == 0) {
              this_.dataForm.groupType = ''
              this_.dataForm.userGroupNumber = null
            } else {
              this_.dataForm.groupType = res.data.groupType.toString()
            }
          } else {
            this.dataForm = {
              userGroupName: '',
              groupType: '',
              groupDescription: '',
              userGroupNumber: null
            }
          }
        })
      },

      // 得到所有组织标签
      getDeptList: function () {
        let this_ = this
        this.utils.request.getDeptList({}, res => {
          if (res.code == '0000') {
            if (this_.deptType == 0) {
              this_.deptOptions = res.data
              this_.currentSelectedDeptId = res.data[0].id
              this_.activeDeptId = res.data[0].id
            }
            this_.queryLabelByDeptId()
          }
        })
      },

      // 组织切换
      handleClick() {
        // 切换时更新用户信息
        let params = {
          id: this.userGroupId,
          deptId: this.currentSelectedDeptId,                   // 切换之前所选部门ID
          labelIds: this.saveAllLabel
        }
        let this_ = this
        this.utils.request.updateLabelTableUserGroups(params, function (res) {
          if (res.code == '0000') {
            // 切换时保存当前所选部门id
            this_.currentSelectedDeptId = this_.activeDeptId
            this_.saveAllLabel = []
            // 切换时保存当前选中标签
            this_.queryLabelByDeptId()
          }
        })
      },

      // 清除所有选择
      resetChecked() {
        this.saveAllLabel = []
        this.$refs.leftTree.setCheckedKeys([])
        this.$refs.rightTree.setCheckedKeys([])
      },

      // 根据部门id获取一二级标签树
      queryLabelByDeptId: function () {
        let this_ = this
        let params = {
          userGroupId: this_.userGroupId,
          deptId: this_.currentSelectedDeptId
        }
        this.utils.request.queryLabelByDeptId(params, res => {
          if (res.code == '0000') {
            this_.labelTree = JSON.parse(JSON.stringify(res.data))
            this_.queryAllLabelByDeptId();
          } else {
            this_.labelTree = []
          }
        })
      },

      // 根据部门id获取二三级标签树
      queryAllLabelByDeptId: function () {
        this.saveAllLabel = []

        let this_ = this
        let params = {
          userGroupId: this_.userGroupId,
          deptId: this_.currentSelectedDeptId
        }
        this.utils.request.queryAllLabelByDeptId(params, res => {
          if (res.code == '0000') {
            this_.labelTree2 = JSON.parse(JSON.stringify(res.data))


            //没有数据加disabled
            let noChilds = JSON.parse(JSON.stringify(res.data)).filter(f => {
              return !f.children;
            }).map(m => { return m.id })
             
            
            this_.labelTree.forEach(f => {
              if (f.children) {
                f.children.forEach(fi => {
                  if (noChilds.includes(fi.id)) {
                    this_.$set(fi, "disabled", true);
                  }
                });
              }
            });


            // 回显所有标签值
            let secondLabel = []
            let threeLabel = []
            this_.labelTree2.forEach(item => {
              this_.$set(item, 'secondStyle', true);
              // 左边树结构
              if (item.children != null) {
                item.children.forEach(item1 => {
                  // 子加pId
                  this_.$set(item1, 'pId', item.id)
                  // 右边树结构
                  if (item1.isChecked) {
                    secondLabel.push(item.id)
                    threeLabel.push(item1.id)
                  }
                })
              }
            })
            this_.$refs.leftTree.setCheckedKeys(secondLabel)
            this_.$refs.rightTree.setCheckedKeys(threeLabel)
            this_.saveAllLabel = threeLabel
          } else {
            this_.labelTree2 = []
          }
        })
      },

      // 左边父级选择右边子级
      checkLeft(a,b) {
        let selectedIds = this.$refs.leftTree.getCheckedKeys();

        let groups = this.labelTree2.filter((f, i) => {
          return selectedIds.includes(f.id)
        })

        groups.forEach(ec => {
          if (ec.children) {
            if(ec.id == a.id){
              this.selectRightIds = this.selectRightIds.concat(ec.children)
            }
          }
        })
        //判断是选中还是取消
        let flag = selectedIds.includes(a.id);
          if (!flag) {
            this.selectRightIds = this.selectRightIds.filter(f => {
              return f.pId != a.id;
            });
          }

        let first = this.labelTree.map(m => {
          return m.id;
        });
        if (first.includes(a.id)) {
          if (b.checkedNodes.length>0) {
            groups.forEach(ec => {
              ec.children.forEach(f => {
                this.selectRightIds = this.selectRightIds.concat(f);
              });
            });
          } else {
            this.selectRightIds = [];
          }
        }

        this.$refs.rightTree.setCheckedNodes(this.selectRightIds)

        // 保存所有选中标签ID
        this.saveAllLabel = this.selectRightIds.map(item => {
          return item.id
        })
      },

      // 右边子级选择左边父级
      checkRight(a, b) {
        let checkedIds = b.checkedKeys.concat(b.halfCheckedKeys)
        this.$refs.leftTree.setCheckedKeys(checkedIds)

        this.selectRightIds = b.checkedNodes.filter(f => {
          return !f.secondStyle;
        });
        // 保存所有选中标签ID
        this.saveAllLabel = this.$refs.rightTree.getCheckedKeys()
      },

      // 开始筛选
      handlerStartScreening() {
        // 是否选中标签
        if (this.deptType == 0) {
          if (this.saveAllLabel.length < 1) {
            let this_ = this
            this_.utils.request.getUserGroupLabelCount({userGroupId: this.userGroupId}, function (res) {
              if (res.code == '0000') {
                if (Number(res.data) <= 0) {
                  this_.$message({message: '请先选择标签', type: 'warning'})
                } else {
                  this_.updateMember()
                }
              }
            })
          } else {
            this.updateMember()
          }
        } else {
          if (this.saveAllLabel.length < 1) {
            this.$message({message: '请先选择标签', type: 'warning'})
          } else {
            this.updateMember()
          }
        }
      },

      //先更新会员在查询
      updateMember() {
        // 先更新会员在查询
        let params = {
          id: this.userGroupId,
          deptId: this.currentSelectedDeptId,
          labelIds: this.saveAllLabel
        }
        let this_ = this
        this.utils.request.updateLabelTableUserGroups(params, function (res) {
          if (res.code == '0000') {
            // 筛选会员
            let params1 = {id: this_.userGroupId}
            this_.utils.request.screeningMember(params1, function (res) {
              if (res.code == '0000') {
                this_.dataForm.userGroupNumber = res.data
                this_.$message({message: '筛选成功', type: 'success'})
              } else {
                this_.$message({message: '筛选失败, ' + res.msg, type: 'error'})
              }
            })
          } else {
            this_.$message({message: '筛选失败, ' + res.msg, type: 'error'})
          }
        })
      },

      // 确认按钮
      handlerSubmit() {
        // 是否选中标签
        if (this.deptType == 0) {
          if (this.saveAllLabel.length < 1) {
            let this_ = this
            this_.utils.request.getUserGroupLabelCount({userGroupId: this.userGroupId}, function (res) {
              if (res.code == '0000') {
                if (Number(res.data) <= 0) {
                  this_.$message({message: '请先选择标签', type: 'warning'})
                } else {
                  this_.addOrUpdateSubmit()
                }
              }
            })
          } else {
            this.addOrUpdateSubmit()
          }
        } else {
          if (this.saveAllLabel.length < 1) {
            this.$message({message: '请先选择标签', type: 'warning'})
          } else {
            this.addOrUpdateSubmit()
          }
        }
      },

      addOrUpdateSubmit() {
        // 保存时默认先筛选用户
        let params = {
          id: this.userGroupId,
          deptId: this.currentSelectedDeptId,
          labelIds: this.saveAllLabel
        }
        let this_ = this
        this_.utils.request.updateLabelTableUserGroups(params, function (res) {
          if (res.code == '0000') {
            // 筛选会员
            let params1 = {id: this_.userGroupId}
            this_.utils.request.screeningMember(params1, function (res) {
              if (res.code == '0000') {
                this_.dataForm.userGroupNumber = res.data
                // 筛选后执行保存
                this_.$refs.dataForm.validate(valid => {
                  if (valid) {
                    let params = Object.assign({}, this_.dataForm)
                    if (params.userGroupNumber <= 0) {
                      this_.$confirm('当前用户组的会员数为0，是否确认保存？', '', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                        closeOnClickModal: false,
                        showClose: false
                      }).then(() => {
                        this_.addOrUpdate(params)
                      }).catch(() => {
                      })
                    } else {
                      this_.addOrUpdate(params)
                    }
                  }
                })
              }
            })
          }
        })
      },
      addOrUpdate(params) {
        let this_ = this
        params.id = this_.userGroupId
        params.deptId = this_.currentSelectedDeptId
        params.labelIds = this_.saveAllLabel
        this_.utils.request.updateUserGroup(params, function (res) {
          if (res.code == '0000') {
            this_.$message({message: '操作成功', type: 'success'})
            this_.$router.push('/pages/AutoMarket/UserGroupManagement/UserGroup')
          } else {
            this_.$message({message: '操作失败' + res.msg, type: 'error'})
          }
        })
      },

      // 取消按钮
      handlerCancel() {
        this.$router.push('/pages/AutoMarket/UserGroupManagement/UserGroup')
      }
    },

    mounted() {
      this.userGroupId = this.$route.params.userGroupId
      this.getUserGroupDetail()
      this.getDeptList()
    }
  }
</script>

<style lang="scss" scoped>
  .deleteAll {
    padding: 0;
  }

  .tree {
    // width: 1200px;
    // margin-top: 10px;
    position: relative;
    display: flex;
    justify-content: flex-start;

    .leftTree {
      padding: 20px;
      width: 218px;
      min-height: 600px;
      left: 0;
      box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.2);
    }

    .rightTree {
      width: 100%;
      min-height: 600px;
      margin-left: 20px;

      .li {
        /deep/ .el-tree {
          .el-tree-node {
            margin-bottom: 20px;
          }

          .el-tree-node__content {
            height: 40px;
            margin: 0;

            .expanded {
              visibility:hidden
            }
            .el-checkbox{
              margin-right: 0;
            }
            .secondStyle {
              width: 100%;
              p{
                height: 40px;
                line-height: 40px;
                background: #ececec;
                position: relative;
                &::before {
                  content: "";
                  width: 40px;
                  height: 40px;
                  position: absolute;
                  left: -40px;
                  top: 0;
                  z-index: 999;
                  background: #ececec;
                }
              }
            }

            .noData {
              display: block;
              width: 100%;
              height: 40px;
              line-height: 40px;
              position: absolute;
              left: 0;
              padding-left: 40px;
            }
          }

          .el-tree-node__children {
            position: relative;
            min-height: 40px;
            display: flex;
            box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.1);
            .noData {
              display: none;
            }
            .el-tree-node__label {
              background: #fff;
            }
            .el-tree-node{
              margin-bottom: 0;
            }
            .el-tree-node__children {
              display: none;
            }
          }
        }
      }
    }
  }

  .tab-container {
    /deep/ .el-tabs {
      .el-tabs__item {
        width: auto;
        padding: 0 24px !important;
      }
    }
    /deep/ .el-tabs{
      .el-tabs__header {
      margin:0 !important
     }
    }
  }

  .desc {
    color: #ffb100;
    font-size: 10px;
    margin-top: 10px;
  }


  /deep/ .el-tabs__nav-prev{
    height: 32px ;
    line-height: 32px;
  }
  /deep/ .el-tabs__nav-next {
    height: 32px ;
    line-height: 32px;
  }
  .mb170{
    margin-bottom: 170px !important;
  }
  .mb20{
    margin-bottom: 20px !important;
  }
  .mb80{
    margin-bottom: 80px !important;
  }
  .mr60{
    margin-right: 60px !important;
  }
  .h32{
    height: 32px;
  }
  .lh32{
    line-height: 32px;
  }
  /deep/ .filterBtn{
    width: 176px ;
    height: 38px;
    font-size: 18px;
  }
</style>
